import execjs
import random
import time
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
import base64
import logging
import requests
import json
import re

# 代理
proxies = {
    'http': '127.0.0.1:7890',
    'https': '127.0.0.1:7890'
}
# 定义日志
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(levelname)s: %(message)s')

def get_html(data):
    """
    处理之后返回正确的html
    :param data:
    :return:
    """
    # 先移除 \r\n
    cleaned_html = data.replace('\r\n', '\n')
    # 如有其它转义继续替换
    cleaned_html = cleaned_html.replace('\\"', '"').replace("\\'", "'")
    # 返回处理后正确的html
    return cleaned_html

def api_ajax(url):
    """
    根据目标站点链接，站点名称，返回解析的资源
    :param url: 站点链接
    :return:
    """

    data = {
        'url': url,
    }
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36',
        'Referer': 'https://snapsave.app'
    }
    result = None
    logging.info('开始请求url, url: %s', url)
    try:
        # 发出请求
        response = requests.request('POST', url='https://snapsave.app/action.php?lang=en', data=data, headers=headers,
                                    proxies=proxies)
        # 响应成功
        if response.status_code == 200:
            # 返回的混淆加密js代码
            js_code = response.text
            # 通过正则稍微eval去除，改成立即执行函数,用msg变量接收
            new_code = re.sub(r'\beval\s*\(', 'var msg = (', js_code)
            # 执行js代码得到明文
            # 使用execjs 需要通过node执行，所以需要先安装node
            ctx = execjs.compile(new_code)
            html = ctx.eval('msg')
            real_html = get_html(html)
            # todo 接下来需要提取链接，然后组装成json返回
            return real_html
        logging.error('请求状态码错误, code: %s', response.status_code)
    except requests.RequestException as e:
        logging.error('请求链接报错，url: %s', url, exc_info=True)

if __name__ == '__main__':
    res = api_ajax('https://www.instagram.com/p/DK7SPUFpbGz/?utm_source=ig_web_copy_link')
    print(res)







